<template>
  <el-form
    ref="ruleFormRef"
    style="max-width: 500px"
    :inline="true"
    :model="formModel"
    :rules="rules"
    label-width="auto"
    class="demo-ruleForm"
    :size="formSize"
    status-icon
  >
    <el-form-item>
      <el-date-picker
        v-model="formModel.startDate"
        disabled
        type="date"
        placeholder="Pick"
        format="YYYY/MM/DD"
        value-format="YYYY-MM-DD"
        @change="datechange"
      />
    </el-form-item>
    <el-form-item label="入住天数" prop="days">
      <el-input-number
        v-model.number="formModel.days"
        clearable
        style="width: 100px"
        :min="1"
        @change="getTotalPrice"
      />
    </el-form-item>
    <el-form-item label="基本信息" style="display: block">
      <el-card>
        <el-form-item label="房间号" prop="roomNumber">
          <el-input v-model="formModel.roomNumber" :disabled="true" />
        </el-form-item>
        <el-form-item label="总价格">
          <el-input v-model="TotalPrice" :disabled="true" />
        </el-form-item>
        <el-form-item label="押金">
          <el-input v-model="deposit" :disabled="true" />
        </el-form-item>
      </el-card>
    </el-form-item>

    <el-row :gutter="20">
      <el-col :span="10">
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="formModel.contact" style="width: 140px" />
        </el-form-item>
      </el-col>
      <el-col :span="14">
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="formModel.phone" style="width: 200px" />
        </el-form-item>
      </el-col>
    </el-row>
    <div v-for="(item, index) in formModel.infoList" :key="index">
      <el-row :gutter="1">
        <!-- 姓名列 -->
        <el-col :span="7">
          <el-form-item
            label="姓名"
            :prop="`infoList.${index}.customerName`"
            :rules="[
              { required: true, message: '姓名不能为空', trigger: 'blur' }
            ]"
          >
            <el-input v-model="item.customerName" style="width: 100px" />
          </el-form-item>
        </el-col>
        <!-- 身份证列 -->
        <el-col :span="12" style="margin-left: 10px">
          <el-form-item
            label="身份证"
            :prop="`infoList.${index}.idCard`"
            :rules="[
              { required: true, message: '身份证不能为空', trigger: 'blur' },
              {
                pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
                message: '身份证格式不正确',
                trigger: 'blur'
              }
            ]"
          >
            <el-input v-model="item.idCard" style="width: 215px" />
          </el-form-item>
        </el-col>
        <!-- 操作按钮列 -->
        <span style="margin-left: 25px">
          <!-- 第一行显示加减号 -->
          <template v-if="index === 0">
            <el-button
              type="primary"
              :icon="Plus"
              circle
              size="small"
              @click="addRow(index)"
            />
            <el-button
              type="danger"
              :icon="Minus"
              circle
              size="small"
              :disabled="formModel.infoList.length === 1"
              @click="removeRow(index)"
            />
          </template>
          <!-- 其他行只显示减号 -->
          <template v-else>
            <el-button
              type="danger"
              :icon="Minus"
              circle
              size="small"
              :disabled="formModel.infoList.length === 1"
              @click="removeRow(index)"
            /> </template
        ></span>
      </el-row>
    </div>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"
        >提交</el-button
      >
      <el-button type="info" @click="reset()">重置</el-button>
      <el-button @click="close">关 闭</el-button>
    </el-form-item>
  </el-form>
  <el-drawer
    v-model="drawer"
    title="选择支付方式"
    direction="btt"
    :before-close="handleClose"
    size="45%"
  >
    <div class="payment-options">
      <div
        v-for="option in paymentOptions"
        :key="option.value"
        class="option"
        :class="{ selected: selectedPayment === option.value }"
        @click="selectPayment(option.value)"
      >
        {{ option.label }}
      </div>
    </div>
    <div class="button-group">
      <el-button type="primary" @click="confirmPayment">确定</el-button>
    </div>
  </el-drawer>
  <!-- 微信支付弹窗 -->
  <el-dialog v-model="wechatDialogVisible" width="300">
    <el-form>
      <el-form-item
        label="应付金额"
        :rules="[
          { required: true, message: '应付金额不能为空', trigger: 'blur' }
        ]"
      >
        <el-input :value="amountToPay" :disabled="true" />
      </el-form-item>
      <el-button @click="calculateChange">支付</el-button>
    </el-form>
  </el-dialog>
  <!-- 现金支付弹窗 -->
  <el-dialog v-model="cashDialogVisible" width="300" @close="handleDialogClose">
    <el-form :model="paymentForm">
      <el-form-item label="实付金额">
        <el-input v-model="paymentForm.paidAmount" />
      </el-form-item>
      <el-form-item
        label="应付金额"
        prop="amountToPay"
        :rules="[
          { required: true, message: '应付金额不能为空', trigger: 'blur' }
        ]"
      >
        <el-input :value="amountToPay" :disabled="true" />
      </el-form-item>
      <el-form-item label="找零金额">
        <el-input :value="change" :disabled="true" />
      </el-form-item>
      <el-button @click="calculateChange">找零</el-button>
    </el-form>
  </el-dialog>
  <!-- 支付宝支付弹窗 -->
  <el-dialog v-model="alipayDialogVisible" width="500">
    <div
      style="
        display: flex;
        align-items: center;
        justify-content: center;
        height: 300px;
      "
    >
      <img :src="imgUrl" alt="" style="width: 300px" />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="refresh">刷新二维码</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref, watch } from "vue";
import {
  ElMessage,
  ElMessageBox,
  type ComponentSize,
  type FormInstance,
  type FormRules
} from "element-plus";

import {
  RoomCheckInForm,
  getPriceTotal,
  addCheckInfo,
  getDepositByRoomNumber,
  cashPay,
  wechatPay,
  CustomerInfo,
  getQrCodeHotel
} from "@/api/roomsale";
import { Plus, Minus, Coin } from "@element-plus/icons-vue";
import { on } from "events";
import { getToken } from "@/utils/auth";

/** ------------------组件通信-接收数据-------------------- */
const emit = defineEmits(["close"]);
const props = defineProps({
  dialogOpen: {
    type: Boolean,
    default: null
  },
  bookingDialogOpen: {
    type: Boolean,
    default: null
  },
  roomNumber: {
    type: String,
    default: null
  },
  bookingData: {
    type: Object,
    default: null
  }
});
// const ruleForm = ref<RoomCheckInForm>({
//   roomNumber: undefined,
//   contact: undefined,
//   phone: undefined,
//   startDate: undefined,
//   days: undefined,
//   information: undefined
// });
interface ExtendedFormModel extends RoomCheckInForm {
  infoList: Array<{ customerName: string; idCard: string }>;
}

const formModel = ref<ExtendedFormModel>({
  // 原有 ruleForm 字段
  roomNumber: undefined,
  contact: undefined,
  phone: undefined,
  startDate: undefined,
  days: undefined,
  information: undefined,
  // 新增动态列表字段
  infoList: [{ customerName: "", idCard: "" }]
});
watch(
  () => props.dialogOpen,
  (newDialogOpen, oldDialogOpen) => {
    if (newDialogOpen === false) {
      close();
    }
  },
  { deep: true, immediate: true }
);
watch(
  () => props.bookingDialogOpen,
  (newbookingDialogOpen, oldbookingDialogOpen) => {
    console.log("watch", props.bookingDialogOpen);
  },
  { deep: true, immediate: true }
);
watch(
  () => props.roomNumber,
  (newroomNumber, oldroomNumber) => {
    formModel.value.roomNumber = newroomNumber;
    console.log("newroomNumber", newroomNumber);
    if (newroomNumber !== "") {
      console.log("initData", newroomNumber);
      initData();
    }
  },
  { deep: true, immediate: true }
);

/** ------------------加载初始化数据-------------------- */
const deposit = ref<number>();
const today = new Date();
// 将字符串日期转换为 Date 对象
function initData() {
  setTimeout(() => {
    formModel.value.startDate =
      today.getFullYear() +
      "-" +
      String(today.getMonth() + 1).padStart(2, "0") +
      "-" +
      String(today.getDate()).padStart(2, "0");
    if (props.bookingDialogOpen) {
      const startDate = new Date(props.bookingData.startDate);
      const leaveDate = new Date(props.bookingData.leaveDate);
      // 计算两个日期之间的毫秒差
      const diffInMilliseconds = leaveDate.getTime() - startDate.getTime();
      // 将毫秒差转换为天数
      const days = diffInMilliseconds / (1000 * 60 * 60 * 24);
      formModel.value.days = days;
      formModel.value.contact = props.bookingData.contact;
      formModel.value.phone = props.bookingData.phone;
      console.log("天数", days);
    } else formModel.value.days = 1;
    getPriceTotal(formModel.value).then(response => {
      TotalPrice.value = response.data;
    });
    getDepositByRoomNumber(formModel.value.roomNumber).then(response => {
      deposit.value = response.data;
    });
  }, 50);
}

/** ------------------表单数据-------------------- */
// 表单属性size
const formSize = ref<ComponentSize>("default");
const ruleFormRef = ref<FormInstance>();
// 定义响应式数组

//表单校验规则
const rules = reactive<FormRules<RoomCheckInForm>>({
  contact: [{ required: true, message: "联系人不能为空", trigger: "blur" }],
  phone: [
    { required: true, message: "电话号码不能为空", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "手机号格式不正确", trigger: "blur" }
  ]
});

// 添加行
// const addRow = (index: number) => {
//   infoList.value.push({ customerName: "", idCard: "" });
// };

// // 删除行
// const removeRow = (index: number) => {
//   if (infoList.value.length > 1) {
//     infoList.value.splice(index, 1);
//   }
// };
const addRow = (index: number) => {
  formModel.value.infoList.push({ customerName: "", idCard: "" });
};

const removeRow = (index: number) => {
  if (formModel.value.infoList.length > 1) {
    formModel.value.infoList.splice(index, 1);
  }
};
let debounceTimer = null;
function getTotalPrice() {
  clearTimeout(debounceTimer);
  debounceTimer = setTimeout(() => {
    getPriceTotal(formModel.value).then(response => {
      TotalPrice.value = response.data;
    });
  }, 300);
}
function datechange() {
  formModel.value.days = 1;
  getPriceTotal(formModel.value).then(response => {
    TotalPrice.value = response.data;
  });
}

const TotalPrice = ref<number>();
const imgUrl = ref("");

const wechatDialogVisible = ref(false);
const alipayDialogVisible = ref(false);
const cashDialogVisible = ref(false);
const paymentDialogVisible = ref(false);
/** 提交表单 */
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      formModel.value.information = formModel.value.infoList
        .map(item => `${item.customerName}:${item.idCard}`)
        .join(",");
      drawer.value = true;
    } else {
      ElMessage.error("表单校验失败，请检查输入！");
    }
  });

  // formModel.value.information = formModel.value.infoList
  //   .map(item => `${item.customerName}:${item.idCard}`)
  //   .join(",");
  // console.log("formModel.value", formModel.value);
  // drawer.value = true;
};

const getQrCodeImg = () => {
  imgUrl.value = `http://kzholm4ampr8.ngrok.xiaomiqiu123.top/hotel/sale/alipay/getQrCode?t=${Date.now()}`;
};

/** 重置表单 */
const resetForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  console.log("resetForm", formModel.value);
};

function reset() {
  resetForm(ruleFormRef.value);
  console.log("reset", formModel.value);
  initData();
  TotalPrice.value = undefined;
  formModel.value.contact = undefined;
  formModel.value.phone = undefined;
  formModel.value.infoList = [
    {
      customerName: "",
      idCard: ""
    }
  ];
}
function refresh() {
  getQrCodeImg();
}

function close() {
  emit("close");
  console.log("关闭后表单里props.roomNumber", props.roomNumber);
}

const drawer = ref(false);

const paymentOptions = [
  { value: "alipay", label: "支付宝支付" },
  { value: "wechat", label: "微信支付" },
  { value: "cash", label: "现金支付" }
];
const selectedPayment = ref("");

const handleClose = done => {
  ElMessageBox.confirm("是否取消支付？")
    .then(() => {
      drawer.value = false;
      done();
    })
    .catch(() => {
      // 取消关闭操作
    });
};

const selectPayment = value => {
  selectedPayment.value = value;
};

const confirmPayment = () => {
  drawer.value = false; // 关闭抽屉，不显示确认弹窗
  closePaymentDialog();
};

//--------------------------------------------------
const closePaymentDialog = () => {
  paymentDialogVisible.value = false;

  switch (selectedPayment.value) {
    case "wechat":
      wechatDialogVisible.value = true;
      break;
    case "alipay":
      alipayDialogVisible.value = true;
      addCheckInfo(formModel.value).then(response => {
        getQrCodeImg();
      });
      break;
    case "cash":
      cashDialogVisible.value = true;
      break;
    default:
      console.log("未选择支付方式");
  }
};

const paymentForm = ref({
  paidAmount: 0
});

// 计算应付金额
const amountToPay = computed(() => {
  return TotalPrice.value + deposit.value;
});

// 计算找零金额
const change = ref<number>();

// 获取总价格的逻辑
const getTotalPayPrice = () => {
  // 这里根据你的业务逻辑来设置 TotalPrice 和 deposit 的值
  TotalPrice.value = 500; // 示例值
  deposit.value = 100; // 示例值
};

// 计算找零金额的逻辑
// 对话框关闭或失焦时清空数据
const handleDialogClose = () => {
  cashDialogVisible.value = false;
  paymentForm.value.paidAmount = 0;
  change.value = 0;
};

// 计算找零方法
const calculateChange = () => {
  if (cashDialogVisible.value === true) {
    alert("现金支付");
    if (!paymentForm.value.paidAmount) {
      ElMessage.warning("请输入实付金额");
      return;
    }
    if (paymentForm.value.paidAmount < amountToPay.value) {
      ElMessage.warning("实付金额不足");
      return;
    }
    change.value = paymentForm.value.paidAmount - amountToPay.value;
    cashPay(formModel.value).then(response => {
      if (response.code === 200) {
        ElMessage({
          type: "success",
          message: response.msg
        });
        cashDialogVisible.value = false;
        close();
      } else {
        ElMessage({
          type: "error",
          message: response.msg
        });
      }
    });
  } else {
    wechatPay(formModel.value).then(response => {
      alert("微信支付");
      if (response.code === 200) {
        ElMessage({
          type: "success",
          message: response.msg
        });
        wechatDialogVisible.value = false;
        close();
      } else {
        ElMessage({
          type: "error",
          message: response.msg
        });
      }
    });
  }
};
/** 关闭窗口 */

//支付宝回调--------------------------
var websocket = null;
var clientId = Math.random().toString(36).substr(2);
const message = "hello world";
//判断当前浏览器是否支持WebSocket
if ("WebSocket" in window) {
  //连接WebSocket节点
  // websocket = new WebSocket("ws://localhost:8080/ws/"+clientId);
  websocket = new WebSocket(
    "ws://kzholm4ampr8.ngrok.xiaomiqiu123.top/ws/" + clientId
  );
} else {
  alert("Not support websocket");
}

//连接发生错误的回调方法
websocket.onerror = function () {
  setMessageInnerHTML("error");
};

//连接成功建立的回调方法
websocket.onopen = function () {
  setMessageInnerHTML("连接成功");
};

//接收到消息的回调方法
websocket.onmessage = function (event) {
  console.log("接收到消息的回调方法onmessage");
  ElMessage({ type: "success", message: event.data });
  alipayDialogVisible.value = true;
  websocket.close();
  close();
};

//连接关闭的回调方法
websocket.onclose = function () {
  setMessageInnerHTML("连接关闭的回调方法close");
};

//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
window.onbeforeunload = function () {
  console.log("关闭窗口");
  websocket.close();
};

//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
  console.log(innerHTML, "-----------", document.getElementById("message"));
  document.getElementById("message").innerHTML += innerHTML + "<br/>";
}

//发送消息
function send() {
  var inputElement = document.getElementById("text") as HTMLInputElement;
  var message = inputElement.value;

  websocket.send(message);
}

//关闭连接
function closeWebSocket() {
  websocket.close();
}
</script>

<style scoped>
.payment-options {
  display: flex;
  flex-direction: column;
  gap: 5px;
  font-size: 16px;
}

.option {
  width: 100%;
  padding: 10px;
  cursor: pointer;
  border: 1px solid #ccc;
}

.selected {
  background-color: #b2eff7;
  border-color: #6ee868;
}

.button-group {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
